<template>
  <div class="app-main-container">
    <div class="app-main-title">
      餐区餐桌
      <div class="goback" @click="$router.go(-1)">
        <i class="el-icon-refresh-left" /> 返回上一页
      </div>
    </div>
    <div class="doumee-filter">
      <el-form inline>
        <el-form-item label="餐桌名称">
          <el-input
            v-model="filters.keyword"
            placeholder="输入餐桌名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="餐桌状态">
          <el-select
            v-model="filters.status"
            placeholder="选择餐桌状态"
            clearable
          >
            <el-option
              v-for="item in goodsStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            v-preventReClick
            type="primary"
            @click="handleCurrentChange(1)"
          >查找</el-button>
          <el-button v-preventReClick @click="clear">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="goosmanager-space-box">
      <div class="box-item goodstype">
        <div class="item-title df_sb">
          <span>餐区</span>
          <el-button
            type="primary"
            size="small"
            @click="showAdd()"
          >
            <i class="el-icon-plus" />添加餐区
          </el-button>
        </div>
        <div class="goodstype_list">
          <div
            v-for="item in goodsArea"
            :key="item.id"
            :class="
              selectGoodsTypeInfo.id === item.id
                ? 'goodstype-item active'
                : 'goodstype-item'
            "
            @click="selectArea(item)"
          >
            <div class="title">{{ item.name }}</div>
            <template>
              <el-popover
                v-model="item.visible"
                placement="top"
                trigger="hover"
                :hover="item.visible"
              >
                <div class="popItems">
                  <el-button
                    size="mini"
                    type="primary"
                    @click="visible = false"
                    @click.stop="editArea(item)"
                  >编辑</el-button>
                  <el-button
                    v-preventReClick
                    type="danger"
                    size="mini"
                    @click="visible = false"
                    @click.stop="deleteGoodsArea(item.id)"
                  >删除</el-button>
                </div>
                <el-button slot="reference" type="info" size="small">
                  <i class="el-icon-more" />
                </el-button>
              </el-popover>
            </template>
          </div>
        </div>
      </div>
      <div v-if="goodsArea.length" class="box-item goodsinfo">
        <el-button type="primary" @click="addTable">新增餐桌</el-button>
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table margin-t-20"
        >
          <el-table-column
            align="center"
            label="餐桌图片"
            min-width="120"
            prop="avatar"
          >
            <template slot-scope="scope">
              <el-image
                fit="contain"
                :src="scope.row.picture"
                :preview-src-list="[scope.row.picture]"
              />
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="餐桌名称"
            min-width="120"
            prop="name"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="餐桌号"
            prop="tableNo"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="状态"
            prop="stock"
            min-width="80"
          >
            <template slot-scope="{ row }">
              <el-switch
                v-model="row.status"
                :active-value="'1'"
                :inactive-value="'0'"
                @change="setSatus(row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            min-width="250"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.status == '0'" class="flex-cc">
                <el-button
                  v-preventReClick
                  type="text"
                  @click="editTable(scope.row.id)"
                >编辑</el-button>
                <el-button
                  v-preventReClick
                  type="text"
                  class="secondColor"
                  @click="delTable(scope.row.id)"
                >删除</el-button>
                <el-button
                  v-preventReClick
                  type="text"
                  @click="downloadQRC(scope.row.id)"
                >下载二维码</el-button>
              </div>
              <div v-else class="flex-cc">
                <el-button
                  v-preventReClick
                  type="text"
                  @click="downloadQRC(scope.row.id)"
                >下载二维码</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div class="flex-cc doumee-pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalCount"
            :current-page.sync="pagination.page"
            hide-on-single-page
            @current-change="handleCurrentChange"
          />
        </div> -->
        <Paginations
          :total="totalCount"
          :page="pagination.page"
          @current-change="handleCurrentChange"
          @SizeChange="handleSizeChange"
        />
      </div>
    </div>
    <!-- 弹框类 -->
    <el-dialog
      :title="areaAdd ? '添加餐区' : '编辑餐区'"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :visible.sync="showAddArea"
    >
      <el-form
        ref="areaForm"
        :model="areaForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="餐区名称" prop="name">
          <el-input v-model="areaForm.name" placeholder="输入餐区名称" maxlength="20" />
        </el-form-item>
        <el-form-item label="排序码" prop="sort">
          <el-input v-model="areaForm.sort" placeholder="输入排序码" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelArea">取消</el-button>
        <el-button v-preventReClick type="primary" @click="confirmArea">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="tableAdd ? '添加餐桌' : '编辑餐桌'"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      :visible.sync="showAddtable"
    >
      <el-form
        ref="tableForm"
        :model="tableForm"
        :rules="tableRules"
        label-width="100px"
      >
        <el-form-item label="餐桌名称" prop="name">
          <el-input v-model="tableForm.name" placeholder="输入餐桌名称" maxlength="20" />
        </el-form-item>
        <el-form-item label="餐桌号" prop="tableNo">
          <el-input v-model="tableForm.tableNo" placeholder="输入餐桌号" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" maxlength="10" />
        </el-form-item>
        <el-form-item label="餐桌图片" prop="configPicture">
          <transition name="fade">
            <Cropper
              v-if="dialogCropperVisible"
              :option-img="optionImg"
              :fileinfo="fileinfo"
              use-type="GOODS_IMG"
              :fixed-number="[32, 32]"
              @formSubmit="cropperSubmit"
              @formClose="cropperClose"
            />
          </transition>
          <el-upload
            class="device-uploader"
            :action="uploadFileUrl"
            :data="uploadData"
            :show-file-list="false"
            accept=".jpg,.png"
            :on-change="addFileChange"
          >
            <i
              v-show="!tableForm.configPicture"
              class="el-icon-plus uploader-icon"
            />
            <div
              v-show="tableForm.configPicture"
              class="file"
              style="width: 82px"
              :style="'background-image: url(' + tableForm.configPicture + ')'"
            >
              <div class="delete">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage"
                />
              </div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="座位数" prop="seatNum">
          <el-input
            v-model="tableForm.seatNum"
            oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            placeholder="输入座位数"
            maxlength="10"
          />
        </el-form-item>
        <el-form-item label="是否上架" prop="status">
          <el-switch
            v-model="tableForm.status"
            :active-value="'1'"
            :inactive-value="'0'"
          />
        </el-form-item>
        <el-form-item label="排序码" prop="sort">
          <el-input v-model="tableForm.sort" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" maxlength="10" placeholder="输入排序码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelTable">取消</el-button>
        <el-button v-preventReClick type="primary" @click="confirmTable">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  goodsTableList,
  goodsTableRemove,
  goodsTableSave,
  goodsTableEdit,
  goodsTableDetail,
  getQRCode,
  goodsAreaList,
  goodsAreaEdit,
  goodsAreaDel,
  goodsAreaAdd,
  uploadFile
} from '@/api'
import store from '@/store'
import Cropper from '@/components/cropper'
export default {
  name: 'DinnerTable',
  components: {
    Cropper
  },
  data() {
    return {
      goodsRestaurantId: '',
      modalDialog: store.getters.dialog,
      uploadFileUrl: uploadFile,
      dialogCropperVisible: false,
      files: {},
      fileinfo: {},
      filters: {},
      goodsStatus: [
        { label: '未上架', value: 0 },
        { label: '已上架', value: 1 }
      ],
      listLoading: false,
      uploadData: {
        folder: 'GOODS_IMG',
        type: ''
      },
      list: [],
      goodsArea: [],
      selectGoodsTypeInfo: null,
      totalCount: 0,
      pagination: {
        page: 1,
        rows: 10
      },
      areaAdd: true,
      showAddArea: false,
      areaForm: {},
      showAddtable: false,
      tableAdd: true,
      tableForm: {
        configPicture: ''
      },
      rules: {
        name: [{ required: true, message: '请输入餐区名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序码', trigger: 'blur' }]
      },
      tableRules: {
        name: [{ required: true, message: '请输入餐桌名称', trigger: 'blur' }],
        tableNo: [{ required: true, message: '请输入餐桌号', trigger: 'blur' }],
        configPicture: [
          { required: true, message: '请上传餐桌图片', trigger: 'change' }
        ],
        sort: [{ required: true, message: '请输入排序码', trigger: 'blur' }],
        seatNum: [{ required: true, message: '请输入座位数', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.goodsRestaurantId = this.$route.query.id || ''
    this.getAreaList(true)
  },
  methods: {
    /**
     * @desc 获取餐区列表
     * @param {是否初始化请求} isFirst
     */
    getAreaList(isFirst) {
      goodsAreaList({
        param: {
          goodsRestaurantId: this.$route.query.id,
          venueId: sessionStorage.getItem('venueId')
        }
      }).then((res) => {
        if (res.errorCode === '000000') {
          this.goodsArea = res.recordList
          if (
            (isFirst && this.goodsArea.length > 0) ||
            !this.selectGoodsTypeInfo
          ) {
            this.selectGoodsTypeInfo = this.goodsArea[0]
            this.handleCurrentChange(1)
          }
        }
      })
    },
    clear() {
      this.filters = {}
      this.handleCurrentChange(1)
    },
    /**
     * @desc 新增餐区
     */
    showAdd() {
      this.addArea = true
      this.showAddArea = true
      this.areaForm = {}
    },
    /**
     * @desc 编辑餐区
     * @param {餐区模型} item
     */
    editArea(item) {
      this.addArea = false
      this.showAddArea = true
      this.areaForm = item
    },
    /**
     * 选餐区
     * @param {选中的餐区} item
     */
    selectArea(item) {
      this.selectGoodsTypeInfo = item
      this.handleCurrentChange(1)
    },
    /**
     * @desc 取消编辑、新增
     */
    cancelArea() {
      this.showAddArea = false
    },
    /**
     * @desc 餐区提交编辑/新增
     */
    confirmArea() {
      this.$refs.areaForm.validate((valid) => {
        if (valid) {
          const action = this.areaForm.id ? goodsAreaEdit : goodsAreaAdd
          action({
            param: {
              ...this.areaForm,
              goodsRestaurantId: this.goodsRestaurantId,
              venueId: sessionStorage.getItem('venueId')
            }
          })
            .then((res) => {
              // console.log('编辑', res)
              if (res.errorCode === '000000') {
                this.$message.success('成功')
                this.showAddArea = false
                this.getAreaList(false)
              }
            })
            .catch(() => {})
        }
      })
    },
    /**
     * @desc 删除餐区
     * @param {餐区id} id
     */
    deleteGoodsArea(id) {
      goodsAreaDel({ param: { id }})
        .then((res) => {
          if (res.errorCode === '000000') {
            this.$message.success('删除成功')
            this.getAreaList(false)
          }
        })
        .catch(() => {})
    },
    /**
     * @desc 新增餐桌
     */
    addTable() {
      this.showAddtable = true
      this.tableAdd = true
      this.tableForm = {
        status: '0'
      }
    },
    /**
     * 修改餐桌状态
     * @param {餐桌模型} row
     */
    setSatus(row) {
      goodsTableEdit({
        param: {
          ...row,
          goodsAreaId: this.selectGoodsTypeInfo.id,
          venueId: sessionStorage.getItem('venueId')
        }
      }).then((res) => {
        if (res.errorCode === '000000') {
          this.$message.success('修改成功')
          this.showAddtable = false
          this.handleCurrentChange(1)
        }
      })
    },
    /**
     * @desc 编辑餐桌
     * @param {餐桌id} id
     */
    editTable(id) {
      goodsTableDetail({ param: { id }})
        .then((res) => {
          if (res.errorCode === '000000') {
            this.tableForm = res.record
            this.$set(this.tableForm, 'configPicture', this.tableForm.picture)
            this.tableForm.picture = this.tableForm.path
            this.showAddtable = true
            this.tableAdd = false
          }
        })
        .catch(() => {})
    },
    /**
     * @desc 上传图片成功回调
     * @param {*} response
     * @param {*} file
     * @param {文件} fileList
     */
    uploadSuccess(response, file, fileList) {
      this.tableForm.picture = response.insertUrl
      this.$set(this.tableForm, 'configPicture', response.showUrl)
      // this.tableForm. = response.showUrl
      this.$refs.tableForm.clearValidate()
    },
    // 上传图片，开始裁剪
    async addFileChange(file) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.tableForm.picture = config.insertUrl
        this.$set(this.tableForm, 'configPicture', config.showUrl)
        // this.tableForm. = response.showUrl
        this.$refs.tableForm.clearValidate()
        this.fileinfo = config
        // this.$refs.ruleForm.clearValidate();
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || '上传失败')
        // this.$refs.ruleForm.clearValidate();
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    /**
     * @desc 取消餐区弹框
     */
    cancelTable() {
      this.showAddtable = false
    },
    /**
     * @desc 保存餐桌
     */
    confirmTable() {
      this.$refs.tableForm.validate((valid) => {
        if (valid) {
          if (this.tableForm.id) {
            this.setSatus(this.tableForm)
          } else {
            goodsTableSave({
              param: {
                ...this.tableForm,
                goodsAreaId: this.selectGoodsTypeInfo.id,
                venueId: sessionStorage.getItem('venueId')
              }
            }).then((res) => {
              if (res.errorCode === '000000') {
                this.$message.success('保存成功')
                this.showAddtable = false
                this.handleCurrentChange(1)
              }
            })
          }
        }
      })
    },
    /**
     * @desc 获取餐桌列表
     * @param {页码} page
     */
    handleSizeChange(value) {
      this.pagination.rows = value
      this.handleCurrentChange(1)
    },
    handleCurrentChange(page) {
      if (page !== undefined) {
        this.pagination.page = page
      }
      goodsTableList({
        pagination: { ...this.pagination },
        param: {
          ...this.filters,
          goodsAreaId: this.selectGoodsTypeInfo.id,
          venueId: sessionStorage.getItem('venueId')
        }
      }).then((res) => {
        if (res.errorCode === '000000') {
          this.list = res.recordList
          this.totalCount = res.totalCount
        }
      })
    },
    /**
     * 删除餐桌
     * @param {餐桌id} id
     */
    delTable(id) {
      const that = this
      this.$confirm('是否要删除该餐桌？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          goodsTableRemove({ param: { id }}).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success('删除成功')
              that.handleCurrentChange(1)
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    deleteDeviceConfigAddImage() {
      this.tableForm.picture = ''
      this.$set(this.tableForm, 'configPicture', '')
    },
    /**
     * 下载餐桌二维码
     * @param {餐桌id} id
     */
    downloadQRC(id) {
      getQRCode({
        param: {
          goodsTableId: id,
          venueId: sessionStorage.getItem('venueId')
        }
      }).then((res) => {
        if (res.errorCode === '000000') {
          var name = new Date().getTime()
          this.downloadIamge(res.record.url, `${name}`)
        }
      })
    },
    downloadIamge(imgsrc, name) {
      // 下载图片地址和图片名
      window.open(imgsrc)
      // var image = new Image()
      // // 解决跨域 Canvas 污染问题
      // image.setAttribute('crossOrigin', 'anonymous')
      // image.onload = function() {
      //   var canvas = document.createElement('canvas')
      //   canvas.width = image.width
      //   canvas.height = image.height
      //   var context = canvas.getContext('2d')
      //   context.drawImage(image, 0, 0, image.width, image.height)
      //   var url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
      //   var a = document.createElement('a') // 生成一个a元素
      //   var event = new MouseEvent('click') // 创建一个单击事件
      //   a.download = name || 'photo' // 设置图片名称
      //   a.href = url // 将生成的URL设置为a.href属性
      //   a.dispatchEvent(event) // 触发a的单击事件
      // }
      // image.src = imgsrc
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.dinner-table,
.goosmanager-space-box {
  display: flex;
  position: relative;
  height: calc(100% - 226px);
  box-sizing: border-box;
  .box-item {
    .item-title {
      font-weight: 500;
      font-size: 22px;
      color: #111;
    }
    .goodstype-item {
      background-color: #f7f7f7;
      padding: 20px;
      border-radius: 4px;
      margin-top: 5px;
      border: 1px solid #fff;
      // margin-right: 10px;
      cursor: pointer;
      display: flex;
      justify-content: space-between;
      .popItems {
        display: flex;
        flex-direction: column;
        // align-items: flex-start;
        // justify-content: flex-start;
      }
    }
    .goodstype-item.active {
      border: 1px solid $menuActive;
      background-color: #f4f7fc;
    }
  }
  .box-item.goodstype {
    width: 300px;
    padding-right: 30px;
    height: 100%;
    overflow-y: auto;
  }
  .box-item.goodsinfo {
    flex: 1;
    min-width: 0;
    height: 100%;
    overflow-y: auto;
  }
}
.goodstype_list{
  height: 500px;
  overflow: auto;
}
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
</style>
